package com.moshang.blog.controller.back.system;

import com.baomidou.mybatisplus.core.conditions.Condition;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Maps;
import com.moshang.blog.core.annotation.SystemLog;
import com.moshang.blog.entity.SysMenu;
import com.moshang.blog.core.constant.MySysUser;
import com.moshang.blog.service.SysMenuService;
import com.moshang.blog.core.utils.RestResponse;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.util.Date;
import java.util.Map;

/**
 * @program: blog
 * @description: 菜单管理
 * @author: xieweiwei
 * @create: 2018-10-26 10:06
 **/
@Controller
@RequestMapping("/back/system/menu")
public class MenuController {
    @Autowired
    private SysMenuService menuService;

    @RequestMapping("list")
    public String showMenuList(){

        return "back/system/menu/sysList";
    }


    @ApiOperation(value = "/treelist", httpMethod = "POST", notes = "展示菜单")
    @RequiresPermissions("sys:menu:list")
    @PostMapping("treelist")
    @ResponseBody
    public RestResponse treelist(){
        Map<String,Object> map = Maps.newHashMap();
        map.put("parentId",null);
        map.put("isShow",false);
        return RestResponse.success().setData(menuService.selectAllMenus(map));
    }

    /**
     * 进入添加根菜单页面
     * @param parentId
     * @param model
     * @return
     */

    @GetMapping("addUI")
    public String addUI(@RequestParam(value = "parentId",required = false) Long parentId, Model model){
        if(parentId != null){
            SysMenu menu = menuService.getById(parentId);
            model.addAttribute("parentMenu",menu);
        }
        return "back/system/menu/add";
    }

    @ApiOperation(value = "/add", httpMethod = "POST", notes = "添加菜单")
    @RequiresPermissions("sys:menu:add")
    @PostMapping("add")
    @ResponseBody
    @SystemLog("保存新增菜单数据")
    public RestResponse add(SysMenu menu){
        if(StringUtils.isBlank(menu.getName())){
            return RestResponse.failure("菜单名称不能为空");
        }
        if(menuService.getCountByName(menu.getName())>0){
            return RestResponse.failure("菜单名称已存在");
        }
        if(StringUtils.isNotBlank(menu.getPermission())){
            if(menuService.getCountByPermission(menu.getPermission())>0){
                return RestResponse.failure("权限标识已经存在");
            }
        }
        if(menu.getParentId() == null){
            menu.setLevel(1);
            QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
            Object o1 = menuService.getObj(wrapper.select("max(sort) as sort").isNull("parent_id"),(o) -> {
                return Integer.parseInt(o.toString());
            });
            int sort = 0;
            if(o1 != null){
                sort =  (Integer)o1 +10;
            }
            menu.setSort(sort);
        }else{
            SysMenu parentMenu = menuService.getById(menu.getParentId());
            if(parentMenu==null){
                return RestResponse.failure("父菜单不存在");
            }
            menu.setParentIds(parentMenu.getParentIds());
            menu.setLevel(parentMenu.getLevel()+1);
            QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
            Object o1 = menuService.getObj(wrapper.select("max(sort) as sort").eq("parent_id",menu.getParentId()),(o) -> {
                return Integer.parseInt(o.toString());
            });
            int sort = 0;
            if(o1 != null){
                sort =  (Integer)o1 +10;
            }
            menu.setSort(sort);
        }
        menu.setCreateBy(MySysUser.currentUser().getId());
        menu.setUpdateBy(MySysUser.currentUser().getId());
        menu.setCreateTime(new Date());
        menu.setUpdateTime(new Date());
        menu.setIsActivited(0);
        menuService.saveOrUpdateMenu(menu);
        menu.setParentIds( StringUtils.isBlank(menu.getParentIds()) ?menu.getId()+",":menu.getParentIds()+menu.getId()+",");
        menuService.saveOrUpdateMenu(menu);
        return RestResponse.success();
    }
    @GetMapping("editUI")
    public String editUI(Long id,Model model){
        SysMenu menu = menuService.getById(id);
        model.addAttribute("menu",menu);
        return "back/system/menu/edit";
    }

    @RequiresPermissions("sys:menu:edit")
    @PostMapping("edit")
    @ResponseBody
    @SystemLog("保存编辑菜单数据")
    @ApiOperation(value = "/edit", httpMethod = "POST", notes = "修改菜单")
    public RestResponse edit(SysMenu menu){
        if(menu.getId() == null){
            return RestResponse.failure("菜单ID不能为空");
        }
        if (StringUtils.isBlank(menu.getName())) {
            return RestResponse.failure("菜单名称不能为空");
        }
        SysMenu oldMenu = menuService.getById(menu.getId());
        if(!oldMenu.getName().equals(menu.getName())) {
            if(menuService.getCountByName(menu.getName())>0){
                return RestResponse.failure("菜单名称已存在");
            }
        }
        if (StringUtils.isNotBlank(menu.getPermission())) {
            if(!oldMenu.getPermission().equals(menu.getPermission())) {
                if (menuService.getCountByPermission(menu.getPermission()) > 0) {
                    return RestResponse.failure("权限标识已经存在");
                }
            }
        }
        if(menu.getSort() == null){
            return RestResponse.failure("排序值不能为空");
        }
        menuService.saveOrUpdateMenu(menu);
        return RestResponse.success();
    }

    /**
     * 逻辑删除
     * @param id
     * @return
     */
    @RequiresPermissions("sys:menu:delete")
    @PostMapping("delete")
    @ResponseBody
    @SystemLog("删除菜单")
    @ApiOperation(value = "/delete", httpMethod = "POST", notes = "删除菜单")
    public RestResponse delete(@RequestParam(value = "id",required = false)Long id){
        if(id == null){
            return RestResponse.failure("菜单ID不能为空");
        }
        SysMenu menu = menuService.getById(id);
        menu.setIsActivited(1);
        menuService.saveOrUpdateMenu(menu);
        return RestResponse.success();
    }
}
